// Release/video/video.js
const app = getApp();
const DB = wx.cloud.database()
var that;
var util = require('../../utils/util');
Page({
  data: {
    // 视频
    videoUrl: '',
    ttval: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  // 选择视频
  xuanzhe_video() {
    var that = this
    //选择上传视频
    wx.chooseVideo({
      sourceType: ['camera', 'album'], //视频选择的来源
      // sizeType: ['compressed'],
      compressed: true, //是否压缩上传视频
      maxDuration: 50, //拍摄时长
      camera: 'back', //默认拉起的是前置或者后置摄像头
      success: function(res) {
        that.setData({
          videoUrl: res.tempFilePath
        })
      }
    })
  },

  // 点击发布视频
  clickVideoUp() {
    that.up_video();
  },
  // 上传视频
  up_video() {
    var date = new Date().getTime()
    console.log('this.data.videoUrl,', this.data.videoUrl)
    wx.cloud.uploadFile({
      cloudPath: 'video/' + date + '.mp4',
      filePath: this.data.videoUrl, // 文件路径
    }).then(res => {
      console.log('res', res)
      that.add_video(res.fileID)
    }).catch(error => {
      // handle error
    })
  },

  // 上传视频记录添加到数据库
  add_video(fileID) {
    var userInfo = wx.getStorageSync('user')
    var data = {
      text: this.data.ttval,
      video: fileID,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      time: util.formatTime(new Date()),
      openId: userInfo._openId
    };
    console.log('data', data)
    DB.collection('video').add({
      // data 字段表示需新增的 JSON 数据
      data: data
    }).then(res => {
      console.log(res)
      wx.showToast({
        title: '发布视频成功',
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/userinfo/myinfo',
        })
      }, 2000)
    })
  },
  bindKeyInput: function(e) {
    this.setData({
      ttval: e.detail.value
    })
  },
})